import { GridActionsCellItem } from "@mui/x-data-grid";
import React from "react";
import { useEffect } from "react";
import { useContext } from "react";
import Dataform from "../../../components/Dataform";
import { TitleContext } from "../../../router";

import DeleteIcon from "@mui/icons-material/DeleteOutlined";
import { useState } from "react";
import ConfirmDialog from "../../../components/ConfirmDialog";
import { Box, Button, Grid, Paper, TextField, Tooltip } from "@mui/material";
import RestartAltIcon from "@mui/icons-material/RestartAlt";
import { renderCellExpand } from "../../../components/RenderCellExpand";
import { useMutation } from "@tanstack/react-query";
import { mutateQueryFn } from "../../../query/mutateQueryFn";
import {
  GET_ALL_ACCOUNT,
  GET_CLASS_URL,
  HANDLE_STUDENT_ACCOUNT,
  PASSWORD_RESET,
} from "../../../constants/url";
import { useSnackbar } from "notistack";
import Class from "./Class";
import { createContext } from "react";
import Loading from "../../../components/loading";
import LoadingButton from "../../../components/LoadingButton";

export const classContext = createContext();
export default function StudentAccount() {
  const nowTitle = useContext(TitleContext);
  useEffect(() => {
    nowTitle.setnowTitle(1);
  }, []);
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [dialogData, setDialogData] = useState({});
  const [mx, setMx] = useState();
  const [rows, setRows] = useState([]);
  const { enqueueSnackbar } = useSnackbar();
  const [newClass, setNewClass] = useState({});
  const [tmpSuccess, setTmpSuccess] = useState();
  const handleDelete = (id) => {
    setConfirmOpen(false);
    //这里执行删除操作
    changeMutate({
      url: HANDLE_STUDENT_ACCOUNT,
      method: "delete",
      params: { id: id },
      useToken: true,
    });
    setRows(rows.filter((t) => t.id != id));
  };

  const handleDeleteClick = (e) => {
    setDialogData({
      text: "你确定要删除id为" + e + "的账号吗？",
      handleClose: () => setConfirmOpen(false),
      handleConfirm: () => handleDelete(e),
    });
    setConfirmOpen(true);
  };

  const handleReset = (id) => {
    setConfirmOpen(false);
    //在这里进行密码重置
    changeMutate({
      url: PASSWORD_RESET,
      method: "get",
      params: {
        user: rows.filter((val) => val.id == id)[0].userId,
      },
      useToken: true,
    });
  };

  const handleResetPwdClick = (e) => {
    setDialogData({
      text: "你确定要将此账号的密码重置为123456吗？",
      handleClose: () => setConfirmOpen(false),
      handleConfirm: () => handleReset(e),
    });
    setConfirmOpen(true);
  };
  const columns = [
    {
      field: "id",
      headerName: "序号",
      // flex: 1,
      width: 20,
      editable: false,
    },
    {
      field: "userId",
      headerName: "学号",
      renderCell: renderCellExpand,
      flex: 4,
      editable: true,
    },
    {
      field: "name",
      headerName: "姓名",
      renderCell: renderCellExpand,
      flex: 4,
      editable: true,
    },
    {
      field: "gender",
      headerName: "性别",
      flex: 2,
      editable: true,
    },
    {
      field: "major",
      renderCell: renderCellExpand,
      headerName: "专业",
      flex: 5,
      editable: true,
    },
    {
      field: "classId",
      headerName: "班级",
      width: 300,
      renderCell: Class,
    },

    {
      field: "actions",
      type: "actions",
      headerName: "操作",
      width: 100,
      cellClassName: "actions",
      getActions: ({ id }) => {
        return [
          <Tooltip title="删除账号">
            <GridActionsCellItem
              icon={<DeleteIcon />}
              label="Delete"
              onClick={() => handleDeleteClick(id)}
              color="inherit"
            />
          </Tooltip>,
          <Tooltip title="重置密码">
            <GridActionsCellItem
              icon={<RestartAltIcon />}
              label="重置密码"
              onClick={() => handleResetPwdClick(id)}
              color="inherit"
            />
          </Tooltip>,
        ];
      },
    },
  ];

  const {
    isLoading: getLoading,
    isSuccess: getSuccess,
    isError: getError,
    mutate: getMutate,
    data: getData,
  } = useMutation(["getAccountInfo"], mutateQueryFn);

  const {
    isLoading: changeLoading,
    isSuccess: changeSuccess,
    isError: changeError,
    mutate: changeMutate,
  } = useMutation(["changeAccount"], mutateQueryFn);

  useEffect(() => {
    getMutate({
      url: GET_ALL_ACCOUNT,
      method: "get",
      params: { role: 2 },
      useToken: true,
    });
  }, []);
  const {
    isLoading: getClassLoading,
    isSuccess: getClassSuccess,
    data: classNames,
    mutate: getClassMutate,
  } = useMutation(["getClassNames"], mutateQueryFn);
  useEffect(() => {
    getClassMutate({
      url: GET_CLASS_URL,
      method: "get",
      useToken: true,
    });
  }, []);

  useEffect(() => {
    if (getSuccess) {
      setRows(
        getData.data.data.map((val, index) => {
          return {
            ...val,
            gender: val.gender == "男" || val.gender == "MALE" ? "男" : "女",
            tid: index + 1,
          };
        })
      );
    }
  }, [getSuccess]);

  useEffect(() => {
    if (changeSuccess) {
      enqueueSnackbar("信息修改成功", { variant: "success" });
      findMax();
      getMutate({
        url: GET_ALL_ACCOUNT,
        method: "get",
        params: { role: 2 },
        useToken: true,
      });
    }
  }, [changeSuccess]);

  const handleChange = (newRow) => {
    //在这里发起请求
    // console.log(newRow);
    delete newRow.birthday;

    delete newRow.avatar;
    changeMutate({
      url: HANDLE_STUDENT_ACCOUNT,
      method: newRow.id > mx ? "put" : "post",
      params:
        newRow.id > mx
          ? {}
          : {
              id: newRow.id,
            },
      data: newRow,
      useToken: true,
    });

    return newRow;
  };

  const findMax = () => {
    var mx = 0;
    for (var i in rows) {
      if (rows[i].id > mx) mx = rows[i].id;
    }
    setMx(mx);
    return mx + 1;
  };
  const {
    isLoading: newClassLoading,
    isSuccess: newClassSuccess,
    isError: newClassError,
    mutate: newClassMutate,
  } = useMutation(["putNewClass"], mutateQueryFn);

  const handleNewClass = () => {
    if (!newClass.className || !newClass.grade) {
      enqueueSnackbar("班级名称和年级不能为空", { variant: "warning" });
      return;
    }
    newClassMutate({
      url: GET_CLASS_URL,
      method: "put",
      data: newClass,
      useToken: true,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
  };
  useEffect(() => {
    if (newClassSuccess) {
      getClassMutate({
        url: GET_CLASS_URL,
        method: "get",
        useToken: true,
      });
      setTmpSuccess(true);
      setTimeout(() => setTmpSuccess(false), 500);
    }
  }, [newClassSuccess]);
  return (
    <div>
      <Grid container spacing={2}>
        <Grid item xs={3}>
          <Paper
            elevation={3}
            sx={{
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              height: 300,
              padding: 5,
              justifyContent: "center",
            }}
          >
            <TextField
              label="新班级名称"
              value={newClass.className}
              onChange={(e) =>
                setNewClass({ ...newClass, className: e.target.value })
              }
            ></TextField>

            <TextField
              sx={{ marginTop: 2 }}
              label="年级"
              value={newClass.grade}
              onChange={(e) =>
                setNewClass({ ...newClass, grade: e.target.value })
              }
            ></TextField>
            <Box sx={{ marginTop: 3 }}>
              <LoadingButton
                clickr={handleNewClass}
                showRight={true}
                isSuccess={tmpSuccess}
                isFetching={newClassLoading}
                // sx={{ marginTop: 3 }}
                variant="contained"
                titler={tmpSuccess ? "创建成功" : "创建新班级"}
              ></LoadingButton>
            </Box>
          </Paper>
        </Grid>
        <Grid item xs={9}>
          {getClassLoading && <Loading />}
          {!getClassLoading && getClassSuccess && (
            <classContext.Provider
              value={{ classNames: classNames.data.data, handleChange }}
            >
              <Box
                sx={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                }}
              >
                <Dataform
                  fileName="学生信息"
                  processRowUpdate={handleChange}
                  rows={rows}
                  columns={columns}
                  loading={getLoading || changeLoading}
                />
                <Button
                  variant="contained"
                  onClick={() => {
                    setRows([
                      ...rows,
                      {
                        id: findMax(),
                        userId: "待完善",
                        name: "待完善",
                        gender: "待完善",
                        major: "待完善",
                        classId: 1,
                      },
                    ]);
                  }}
                  sx={{ marginTop: 4 }}
                >
                  添加新账号
                </Button>
                <ConfirmDialog {...dialogData} open={confirmOpen} />
              </Box>
            </classContext.Provider>
          )}
        </Grid>
      </Grid>
    </div>
  );
}
